package top.kaoshanji.p2ch10c;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 代码清单-p2ch10c-185页a：添加了验证器的控制器
 * @author kaoshanji
 * ^_^
 * create time 2025/4/8 17:35
 */
@WebServlet(name = "ControllerServlet", urlPatterns = {"/product_input", "/product_save"})
public class ControllerServlet extends HttpServlet {

    private static final long serialVersionUID = 1579L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        process(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        process(req, resp);
    }

    private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求对象的编码
        request.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应编码
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        String uri = request.getRequestURI();

        int lastIndex = uri.lastIndexOf("/");
        String action = uri.substring(lastIndex + 1);
        String dispatchUrl = null;

        if (action.equals("product_input")) {
            dispatchUrl = "/jsp/ProductForm.jsp";
        } else if (action.equals("product_save")) {
            // 创建表单 获取页面表单的数据...用于验证..如果验证不通过就原样返回..不会影响到其他..
            ProductForm productForm = new ProductForm();
            productForm.setName(request.getParameter("name"));
            productForm.setDescription(request.getParameter("description"));
            productForm.setPrice(request.getParameter("price"));

            // 进行验证一下...就用到了 ProductForm 对象
            ProductValidator productValidator = new ProductValidator();
            List<String> errors = productValidator.validate(productForm);

            if (errors.isEmpty()) { // 数据正常
                // 创建 model..内部操作..业务数据..
                Product product = new Product();
                product.setName(productForm.getName());
                product.setDescription(productForm.getDescription());
                product.setPrice(Float.parseFloat(productForm.getPrice()));

                // 执行 action 方法...保存到数据库里
                SaveProductAction saveProductAction = new SaveProductAction();
                saveProductAction.save(product);

                // 保存到 HttpServletRequest 属性上，可以在页面显示
                request.setAttribute("product", product);
                dispatchUrl = "/jsp/ProductDetails.jsp";

            } else { // 说明验证不通过
                request.setAttribute("errors", errors);
                request.setAttribute("form", productForm); // 把页面的数据原样返回
                dispatchUrl = "/jsp/ProductForm.jsp";
            }

        }

        if (dispatchUrl != null) {
            RequestDispatcher requestDispatcher = request.getRequestDispatcher(dispatchUrl); // 这个参数用的妙啊..具体是什么都行
            requestDispatcher.forward(request, response);
        }

    }

}
